package com.sds.reader;

import java.io.IOException;
import java.nio.ByteBuffer;

public class DBFileReader extends AbstractReader {
	
	DBFileReader() {}
	
	public byte[] read(int bytesLength) throws Exception {
		if (!isOpened()) {
			throw new Exception("nono");
		}
		
		byte[] b = new byte[bytesLength];
		try {
			getFileInputStream().read(b, 0, bytesLength);
		} catch (IOException e) {
			
		}
		return b;
	}
	
	public String readString(int bytesLength) throws Exception {
		byte[] b = read(bytesLength);
		
		return new String(b);
	}
	
	public Integer readInteger(int bytesLength) throws Exception {
		byte[] b = read(bytesLength);
		
		int byteMaxSize = Integer.SIZE / Byte.SIZE;	
		if (byteMaxSize < bytesLength) {
			throw new Exception();
		}
		
		byte[] nb = new byte[byteMaxSize];
		for (int i=0 ; i<b.length ; i++) {
			nb[nb.length-b.length+i] = b[i];
		}
		
		ByteBuffer bb = ByteBuffer.allocate(byteMaxSize);
	    bb = ByteBuffer.wrap(nb);	    
		
		return bb.getInt();
	}
}
